<template>
    <el-container>
      <!--     左边栏-->
      <div class="el-aside" style="height: 100%">
        <el-aside width="180px">
          <el-menu
              :default-active="currentPath"
              class="el-menu-vertical-demo"
              @open="handleOpen"
              @close="handleClose"
              @select="handleSelect"
              background-color="#D3DCE6"
              router
              style="margin-top: 30px; text-align: left"
              unique-opened
              ref="menuRef"
          >
            <el-menu-item index="index" style="font-weight: 900">
              <img :src="getUrl('home')" style="width: 20px;height: 20px">
              <span style="margin-left: 20px" data-index="index" ref="indexMenuClick">首页</span>
            </el-menu-item>
            <DefaultComponent :data="data"></DefaultComponent>
          </el-menu>
        </el-aside>
      </div>
      <el-container>
        <el-header style="font-size: 12px">

          <div style="text-align: right;position: relative;top: -11px;left: -20px;">
            <template>
              <el-select v-model="currentCommunityId" placeholder="请选择" @change="currentCommunityChange" style="z-index: 9999">
                <el-option
                    v-for="item in zyCommunityList"
                    :key="item.communityId"
                    :label="item.communityName"
                    :value="item.communityId"
                    >
                </el-option>
              </el-select>
            </template>
            <el-dropdown style="text-align: right;position: relative;top: 15px;margin-left: 20px;z-index: 9999">
              <!--          <i class="el-icon-setting" style="margin-right: 15px"></i>-->
              <!--              <img style="width: 45px;height: 45px;border-radius: 20%"  src="https://hellowold888.oss-cn-hangzhou.aliyuncs.com/hellowold888/images/default.d25a6cc8.gif?Expires=1696732383&OSSAccessKeyId=LTAI5t9tdUXVY7YVyEu6VPBB&Signature=D2tS4G6QFvgvl7EQv%2FeDwlF2yvI%3D" class="avatar">-->
              <img style="width: 45px;height: 45px;border-radius: 20%" :src="user.avatar" class="avatar" >
              <el-dropdown-menu slot="dropdown">
                <!--              <router-link to="/person" style="position: relative;top: 20px">个人中心</router-link>-->
                  <a @click="addPersonTab" style="position: relative;top: 0px">个人中心</a><br>
                  <a href="/logout" style="position: relative;top: 10px">注销</a>

                <!--            <el-dropdown-item>新增</el-dropdown-item>-->
                <!--            <el-dropdown-item>删除</el-dropdown-item>-->

              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-header>
        <el-main style="position: relative;top: -60px">
          <el-breadcrumb style="font-size: 17px" separator="/" >
            <el-breadcrumb-item v-for="path in crumbs.keyPath" >
              {{ path }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <!--        标签页-->
          <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit" @tab-click="tabClickHandler" style="height: 70px;position: relative;top: 25px">
            <el-tab-pane
                :key="item.name"
                v-for="(item, index) in editableTabs"
                :label="item.title"
                :name="item.name"
            >
            </el-tab-pane>
          </el-tabs>
          <router-view></router-view>
        </el-main>
        <el-footer>Footer</el-footer>
      </el-container>
    </el-container>

</template>

<style scoped>
html, body, #app, .el-container {
  height: 100%;
}

/deep/ .el-breadcrumb__separator {
  color: #409EFF;
}

.el-header, .el-footer {
  background-color: #ebeef5;
  color: #ebeef5;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-aside {
  height: 100%;
}

el-submenu {
  background-color: antiquewhite;
  color: #42b983;
}

el-menu-item {
  background-color: aqua;
}
/deep/ .el-breadcrumb__inner {
  color: darkgray;
}
/deep/ .el-submenu__title{
  font-weight: 900;
}



</style>

<script>
import DefaultComponent from "@/views/default-component.vue";

export default {
  components: {
    DefaultComponent,
  },


  name: "test",
  data() {
    return {
      //当前打开菜单
      currentPath: 'index',
      //菜单列表
      systemMenuList: null,
      textPathArr: [],
      //存储在浏览器localStorage里的username
      size: 5,
      username: '',
      editableTabsValue: '1',
      editableTabs: [],
      tabIndex: 2,
      users: "",
      user: {
        userId: 0,
        deptId: "",
        userName: "",
        nickName: "",
        userType: "",
        email: "",
        phonenumber: "",
        sex: "",
        avatar: "",
        password: "",
        status: "",
        createTime: "",
        oldPassword: ""
      },
      //面包屑
      crumbs: {
        key: '',
        keyPath: [],
      },
      data: null,
      sysMenu: {
        menuId: "",
        menuName: "",
        parentId: "",
        orderNum: "",
        path: "",
        component: "",
        isFrame: "",
        isCache: "",
        menuType: "C",
        visible: "",
        status: "",
        perms: "",
        icon: "",
        createBy: "",
        parentMenuName: "",
      },
      // 智慧社区  社区集合
      zyCommunityList:[],
      // 当前的社区Id
      currentCommunityId:"",

    };
  },

  methods: {
    hash() {
      return location.hash.replace("#/", "")
    },
    // 装载系统菜单集合
    loadSystemMenuList() {
      this.axios.get("/sysMenu/list")
          .then(result => {
            this.systemMenuList = result.data.data

          })
    },
    // 装载系统菜单树
    loadSystemMenuTree() {
      //version 2.0
      this.username = localStorage.getItem('username')
      this.axios.get("/sysMenu/treeByusername?username=" + this.username)
          .then(result => {
            this.data = result.data.data;


            for (const systemMenuListElement of this.systemMenuList) {
              if (this.hash() == systemMenuListElement.path) {
                // this.crumbs.key = systemMenuListElement.menuName
                this.sysMenu = systemMenuListElement
              }
            }
            let index=this.hash()
            let indexPath=this.getIndexPath2(index)

            this.$refs.menuRef.$emit('select', index, indexPath);
          })
    },
    //获取user对应用户的头像
    localUsers() {
      this.axios.get("sysUser/" + this.username)
          .then(result => {
            this.user = result.data.data;
          })
    },
    // 导航栏目录打开
    handleOpen(key, keyPath) {

    },
    // 导航栏目录关闭
    handleClose(key, keyPath) {
    },
    // 菜单被选中
    handleSelect(key, keyPath) {

      this.crumbs.keyPath = []

      if (key=='index'){
        this.emptySysMenu()
        this.sysMenu.path='index'
        this.sysMenu.menuName='主页'
        this.crumbs.key='主页'
        this.crumbs.keyPath=['主页']
        this.handleTabsEdit(this.crumbs.key, 'add')
        if (this.hash()!='index'){
          this.$router.push('index')
        }
        return
      }

      //遍历系统菜单集合拿到  面包屑的key的中文
      for (const systemMenuListElement of this.systemMenuList) {
        if (key == systemMenuListElement.path) {
          this.sysMenu = systemMenuListElement
          this.crumbs.key = systemMenuListElement.menuName
        }
      }
      //遍历系统菜单集合拿到  面包屑的key的中文路径
      for (const keyPathElement of keyPath) {
        for (const systemMenuListElement of this.systemMenuList) {
          if (systemMenuListElement.path == keyPathElement) {
            this.crumbs.keyPath.push(systemMenuListElement.menuName)
            break
          }
        }
      }
      this.handleTabsEdit(this.crumbs.key, 'add')
    },
    // todo 添加路由判断
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        for (const editableTab of this.editableTabs) {
          if (editableTab.title == targetName) {
            this.editableTabsValue = editableTab.name
            return
          }
        }
        // let newTabName = ++this.tabIndex + '';
        this.editableTabs.push({
          title: targetName,
          name: JSON.parse(JSON.stringify(this.crumbs.key)),
          component: JSON.parse(JSON.stringify(this.sysMenu.path)),
          crumbs: JSON.parse(JSON.stringify(this.crumbs))
        });
        this.editableTabsValue = JSON.parse(JSON.stringify(this.crumbs.key));
      }
      if (action === 'remove') {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;

        let nextTab=null
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        // 删除选中的tab
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
        //如果标签栏长度为0
        if (this.editableTabs.length == 0) {
          //自动触发事件
          this.$refs.menuRef.$emit('select', "index", ["index"]);
        }
        //变更路由
        this.$router.push(nextTab.component)
        // 变更面包屑
        this.crumbs=nextTab.crumbs

        //通过路由拿到keyPath  如['system','user']
        for (const systemMenuListElement of this.systemMenuList) {
          if (this.editableTabsValue==systemMenuListElement.path){
            this.emptySysMenu()
            this.sysMenu=systemMenuListElement
            //通过菜单导航栏的index拿到keyValue ['system','menu']
            const indexPath = this.$refs.menuRef.getPath(this.editableTabsValue);
          }
        }


      }
    },
    // 获取本地图片地址
    getUrl(value) {
      return require(`@/assets/icons/svg/${value}.svg`)
    },
    tabClickHandler(tab) {
      for (const item of this.editableTabs) {
        if (item.name == tab.name) {
          this.crumbs = item.crumbs
          this.editableTabsValue = item.name
          this.currentPath = item.component
        }
      }
      for (const item of this.editableTabs) {
        if (item.name == tab.name) {
          if (location.hash.replace("#/", "") == item.component) {
            // this.$router.push(item.component)
            return;
          }
          this.$router.push(item.component)
        }
      }
    },
    // 清空单个菜单的所有属性
    emptySysMenu(){
      this.sysMenu={
        menuId: "",
        menuName: "",
        parentId: "",
        orderNum: "",
        path: "",
        component: "",
        isFrame: "",
        isCache: "",
        menuType: "",
        visible: "",
        status: "",
        perms: "",
        icon: "",
        createBy: "",
        parentMenuName: "",
      }
    },
  //   添加用户标签页
    addPersonTab(){
      this.emptySysMenu()
      this.sysMenu.path='person'
      this.sysMenu.menuName='个人信息'
      this.crumbs.key='个人信息'
      this.crumbs.keyPath=['个人信息']
      this.handleTabsEdit(this.crumbs.key, 'add')
      if (this.hash()!='person'){
        this.$router.push('person')
      }
      return
    },
      loginout(){

      },

    //   添加字典数据标签页
    addDictDataTab(){
      this.emptySysMenu()
      this.sysMenu.path='dictData'
      this.sysMenu.menuName='字典数据'
      this.crumbs.key='字典数据'
      this.crumbs.keyPath=['字典管理','字典数据']

      this.handleTabsEdit(this.crumbs.key, 'add')
    },
    //菜单选中的第二个方法
    handleMenuSelect(index) {
      const indexPath = this.getIndexPath(index);
    },
    // 通过菜单索引拿到indexPath
    getIndexPath(index, parentPath = '') {
      let indexPath = parentPath ? [parentPath] : [];
      this.$refs.menuRef.$children.forEach(item => {
        if (item.index === index) {
          indexPath.push(item.index);
        } else if (item.$options.name === 'el-submenu') {
          const subIndexPath = this.getIndexPath(index, item.index);
          if (subIndexPath.length > 1) {
            indexPath = indexPath.concat(subIndexPath);
          }
        }
      });
      return indexPath;
    },
    getIndexPath2(index) {
      const indexPath = [];
      this.findIndexPath(this.data, index, indexPath);
      return indexPath;
    },
    findIndexPath(menuItems, targetIndex, indexPath) {
      for (let i = 0; i < menuItems.length; i++) {
        const item = menuItems[i];
        if (item.path === targetIndex) {
          indexPath.push(item.path);
          return true;
        }

        if (item.children) {
          if (this.findIndexPath(item.children, targetIndex, indexPath)) {
            indexPath.unshift(item.path);
            return true;
          }
        }

      }
      return false;
    },
    // 装载智慧社区社区集合
    loadZyCommunityList(){
      this.axios.get("/zyCommunity/list")
          .then(result=>{
            this.zyCommunityList=result.data.data
          })
    },
    // 当前社区下拉框change事件
    currentCommunityChange(){
      this.$bus.$emit('mainCurrentCommunityChange',this.currentCommunityId)
    }

  },
  created() {
    this.currentPath = location.hash.replace('#/', "")
  },
  mounted() {
    this.loadSystemMenuList()
    this.loadSystemMenuTree()
    this.localUsers(1)
    //导航菜单当前选中项
    if (this.hash() == 'main') {
      //如果登陆后是main，也就是刚登录的话
      this.currentPath = 'index'
      //挂载主页视图
      this.$router.push("/" + this.currentPath)
    } else {
      this.currentPath = this.hash()
    }

    this.$bus.$on('toDictDataView', this.addDictDataTab);
    this.loadZyCommunityList()
  }

}

</script>